import os

from requests import get
from lxml import etree


# 小说基础信息
def get_book():
    home_url = 'https://www.zongheng.com/'

    ret = get(home_url, headers={"Referer": "https://www.zongheng.com/",
                                 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"})

    html = etree.HTML(ret.text)

    a = html.xpath('//*[@id="monthTicketRankList"]/li[1]/a')[0]

    book_url = a.get('href').replace('/book/', '/showchapter/')
    book_name = a.text
    return book_name, book_url


def get_cp(book_url):
    ret = get(book_url, headers={"Referer": "https://www.zongheng.com/",
                                 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"})
    html = etree.HTML(ret.text)

    a = html.xpath('/html/body/div[3]/div[2]/div[2]/div/ul/li/a')
    return {i.text: i.get('href') for i in a}


def get_content(url):
    ret = get(url, headers={"Referer": "https://www.zongheng.com/",
                            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"})
    html = etree.HTML(ret.text)
    p_list = html.xpath("""//*[@id="readerFt"]/div[1]/div[1]/div[contains(@class, 'content')]/p""")
    return "\n".join([p.text for p in p_list])


if __name__ == '__main__':
    bookname, url = get_book()
    # 创建书名文件夹
    os.mkdir(bookname)

    cp = get_cp(url)

    for name, url in cp.items():
        cp_name = name.replace(' ', '_')
        content = get_content(url)

        with open(f"./{bookname}/{cp_name}.txt", 'w') as f:
            f.write(content)
